<?php

class EmailController extends Controller
{
	public function actionIndex()
	{
		echo 123;
	}

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/

	public function actionSendMail() {
		$request = Yii::app()->request;
		$hostname = '{imap.gmail.com:993/imap/ssl/novalidate-cert}[Gmail]/Sent Mail';
		$username = $request->getParam('emailSend');
		$password = $request->getParam('emailPass');

		$title = $request->getParam('titleEmail');
		$content = $request->getParam('contentEmail');
		$timeWait = $request->getParam('waitTime');

        // $inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());

        // var_dump(file_get_contents($_FILES['file']['tmp_name']));

        $mail=Yii::app()->Smtpmail;
        $mail->Username = $username;
        $mail->Password = $password;
        // var_dump($mail); die;

        if (($handle = fopen($_FILES['file']['tmp_name'], "r")) !== FALSE) {
            while (($data = fgetcsv($handle)) !== FALSE) {
                // echo $data[0]."<br>";
		        $mail->ClearAllRecipients();
		        $mail->ClearAttachments();
		        $mail->ClearAddresses();

		        $mail->SetFrom('SendEmail', 'Send Email');
		        $mail->Subject    = $title;
		        $mail->MsgHTML($content);
		        $mail->CharSet = 'UTF-8';
		        // $mail->AddCC($cc);

		        // $address = $data['0'];
		        $mail->AddAddress($data['0']);
		            
		        // if(strlen($subject) > 0 && strlen($body) > 0) {
		        //     Yii::log($mail->serializeMailInfo(),"info","mail_log");
		            if(!$mail->Send()) {
		                // Yii::log("Can not send mail to ".$address, "error", "mail_log");
		                // return false;
		            }else {
		                // Yii::log("Send mail to ".$address." success", "info", "mail_log");
		                // return true;
		            }
		        // }else{
		        //     Yii::log("Not send mail to email: ".$address,"error","mail_log");
		        //     return false;
		        // }

		      	sleep($timeWait);
            }
        }

	}
}